<template>
	<z-paging ref="paging" :auto-clean-list-when-reload="false" :auto-scroll-to-top-when-reload="false"
		v-model="dataList" @query="queryList" :default-page-size='pageSizeCount' :default-page-no='pageNo'>
		<template>
			<view class="">
				<image :src="model.imageUrl" class="topImage" mode=""></image>
				<BtnsView @btnsClick='btnsClick'></BtnsView>
				<view class="btn zsConter mainBgColor" @click="downloadClick()">
					下载
				</view>

			</view>
			<!-- 底部广告 -->
		<!-- 	<view style="padding: 10px;">
				<ad unit-id="adunit-f27f8e100bbac4ab" mode="normal" ad-intervals="60"
					bindload="adOnLoad" bindclose="onClose">
				</ad>
			</view> -->
		</template>

		<view class="flex-row" style="flex-wrap: wrap; padding: 10px;">
			<view @click="clickItem(index)" v-for="(item,index) in dataList" :key="index">
				<ImageCell :dataModel='item'></ImageCell>
			</view>
		</view>
		<uni-popup ref="popup" type="center">
			<shareMomentsView v-if="showSharePopup==true" @closeClick='this.$refs.popup.close()'
				:menuButtonInfo="menuButtonInfo"></shareMomentsView>
		</uni-popup>
	</z-paging>
</template>

<script>
	import ZSSwiper from '../../components/zs-swiper/zs-swiper.vue'
	import ImageCell from '../../components/gif-image-cell/gif-image-cell.vue'
	import BtnsView from '../../components/btns-view/btns-view.vue'
	import shareMomentsView from '../../components/share-moments-view/share-moments-view.vue'

	export default {
		components: {
			ZSSwiper,
			ImageCell,
			BtnsView,
			shareMomentsView
		},
		data() {
			return {
				dataList: [],
				model: {},
				showSharePopup: false,
				menuButtonInfo:{},
				pageSizeCount:20,
				pageNo:0,
				albumNmae:'',
				isAlbum:false
			}
		},
		onLoad(option) {
			
			if(option.model == null){
				this.model = option;
				this.pageSizeCount =  parseInt(this.model.pageSizeCount) 
				this.pageNo =  parseInt(this.model.pageNo)
				this.model.tableType = parseInt(option.tableType);
				if(this.model.isAlbum == 'true'){
					this.isAlbum = true
					this.albumNmae = this.model.albumNmae
				}
				if(this.model.type == 'undefined'){
					this.model.type = undefined;
				}
				
			}else {
				this.model = this.$decodeJson(option.model)
				this.pageSizeCount = this.model.pageSizeCount
				this.pageNo = this.model.pageNo;
				if(this.model.isAlbum == true){
					this.isAlbum = true
					this.albumNmae = this.model.albumNmae
				}
			}
			
			
			console.log('model==',this.model)
			this.loadAd();
			// this.$uniCloudApi.get_data_count(this.model.tableType,this.model.type).then(res=>{
			// 	this.getData(res);
			// });
		},
		onReady() {
		    // 在页面准备好时获取胶囊按钮的位置信息
		    this.menuButtonInfo = uni.getMenuButtonBoundingClientRect();
		    console.log('胶囊信息===',this.menuButtonInfo);
		  },
		methods: {
		
			queryList(pageNo, pageSize) {
				console.log('页面参数===pageNo=', pageNo, 'pageSize=', pageSize)
				if(this.isAlbum == true){
					this.$uniCloudApi.get_album_list('0',this.albumNmae,pageNo,pageSize).then((res) => {
						this.$refs.paging.complete(res);
					}).catch(err => {
						this.$refs.paging.complete([]);
						this.errStr = err.toString();
						uni.showToast({
							title: err.toString(),
							icon: 'none'
						})
					})
				} else {
					this.$uniCloudApi.get_data_list(this.model.tableType,this.model.type, pageNo, pageSize).then((res) => {
						this.$refs.paging.complete(res);
					}).catch(err => {
						this.$refs.paging.complete([]);
						this.errStr = err.toString();
						uni.showToast({
							title: err.toString(),
							icon: 'none'
						})
					})
				}
				
			},
			
			btnsClick(data) {
				if (data.index == 2) {
					this.showSharePopup = true;
					this.$refs.popup.open('center')
				} else {
					var index = this.model.tableType -1;
					console.log('index===',index)
					var pages =['/pages/home-page/home-page','/pages/album-page/album-page','/pages/background-image-page/background-image-page','/pages/avatar-page/avatar-page']
					uni.switchTab({
					  url: pages[index]
					});
					// uni.navigateBack({
					// 	data:-1
					// });
				}
			},
			getShareStr(senderFriend) {
		
				var tableType = this.model.tableType
				var type = this.model.type
				var pageSizeCount = this.pageSizeCount
				var  pageNo = this.pageNo
				var isAlbum = this.model.isAlbum == true? true : false
				var albumNmae = this.albumNmae
				var path = 'pages/details-page/details-page?'
				var imageUrl = this.model.imageUrl;
				var str = `imageUrl=${imageUrl}&sharePush=1&albumNmae=${albumNmae}&isAlbum=${isAlbum}&tableType=${tableType}&type=${type}&pageSizeCount=${pageSizeCount}&pageNo=${pageNo}`
				
				if(senderFriend){
					 str = `${path}imageUrl=${imageUrl}&sharePush=1&albumNmae=${albumNmae}&isAlbum=${isAlbum}&tableType=${tableType}&type=${type}&pageSizeCount=${pageSizeCount}&pageNo=${pageNo}`
				} 
				console.log('getShareStr==',str)
				return str;
			},
			downloadClick(){
				if(this.$publicApi.getIsInfiniteDownload(this.$appConfigureData.maxAdCount)){
					//无限下载
					console.log('可以无限下载==')
					this.clickPreservation()
					return
				} 
				
				let that = this;
				var showTitle = '看完广告可下载'
				if(this.$appConfigureData.openMaxAdCount == '1'){
					showTitle = '最多看'+this.$appConfigureData.maxAdCount+'次广告当天无限下载'
				} 
				uni.showModal({
					showCancel: true,
					title: '温馨提示',
					content: '最多看'+this.$appConfigureData.maxAdCount+'次广告当天无限下载',
					success: function (res) {
							if (res.confirm) {
								// 用户点击确定
								that.showAd()
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
				});
				
			},
			//看视频
			showAd() {
					this.ad.show().then(() => {
						console.log('激励视频广告显示成功');
					}).catch((err) => {
						console.error('激励视频广告显示失败', err);
						this.clickPreservation();
					});
			
			},
			loadAd() {
				if (wx.createRewardedVideoAd) {
					this.ad = wx.createRewardedVideoAd({
						adUnitId: 'adunit-c499d80094dd6fcf'
					});
					this.ad.onLoad(() => {
						console.log('激励视频广告加载成功');
					});
					this.ad.onError((err) => {
						console.error('激励视频广告加载失败', err);
					});
					this.ad.onClose((res) => {
						if (res && res.isEnded) {
							console.log('用户完整观看了广告，可以发放奖励');
							this.clickPreservation();
							this.$publicApi.addSeeAdcount();
						} else {
							console.log('用户未完整观看广告2');
							uni.showModal({
							  title: '温馨提示', // 弹窗的标题
							  content: '观看完整广告才可下载素材', // 弹窗的内容
							  showCancel: false, // 是否显示取消按钮，默认为true
							  confirmText: '确定', // 确定按钮的文字，默认为"确定"
							});
						}
					});
				}
			
			},
			clickPreservation() {
				uni.showLoading({
					title: '保存中'
				})
				// 假设这是你要下载的图片的 URL
				const imageUrl =this.model.imageUrl
				let that = this
				uni.downloadFile({
					url: imageUrl,
					success: (res) => {
							console.log('下载成功过==')
						if (res.statusCode === 200) {
							uni.hideLoading()
							that.detectPermissions(res.tempFilePath);
						} else {
							uni.showToast({
								title: '网络错误',
							});
						}
					},
					
				});
			
			},
			detectPermissions(filePath) {
				// 检查用户是否授权保存相册权限
				wx.getSetting({
					success: (res) => {
						if (!res.authSetting['scope.writePhotosAlbum']) {
							// 用户没有授权，请求授权
							wx.authorize({
								scope: 'scope.writePhotosAlbum',
								success: () => {
									// 用户已授权
									this.saveImageToPhotosAlbum(filePath);
								},
								fail: () => {
									// 用户拒绝授权，可以在这里给出提示或引导用户手动开启权限
									wx.showModal({
										title: '提示',
										content: '需要您授权保存相册权限才能使用该功能',
										showCancel: false,
										success: (res) => {
											wx.openSetting({
												success: (settingRes) => {
													if (settingRes
														.authSetting[
															'scope.writePhotosAlbum'
														]) {
														// 用户在设置页面授权成功
														this.saveImageToPhotosAlbum(
															filePath);
													} else {
														// 用户在设置页面拒绝授权
														wx.showToast({
															title: '保存失败',
															icon: 'none'
														});
													}
												}
											});
										}
									});
								}
							});
						} else {
							// 用户已经授权
							this.saveImageToPhotosAlbum(filePath);
						}
					}
				});
			
			
			},
			// 保存图片到相册的函数
			saveImageToPhotosAlbum(filePath) {
				wx.saveImageToPhotosAlbum({
					filePath: filePath,
					success: function() {
						wx.showToast({
							title: '保存成功',
							icon: 'success'
						});
					},
					fail: function(err) {
						wx.showToast({
							title: '保存失败',
							icon: 'none'
						});
						console.log(err);
					}
				});
			},
			
			
			clickItem(index) {
				var item = this.dataList[index]
				
				var model = {
					'imageUrl': item.imageUrl,
					'tableType': this.model.tableType,
					'type': item.type,
					"pageSizeCount": this.pageSizeCount,
					'pageNo': this.pageNo
				}
				if(this.model.isAlbum == true){
					model.isAlbum = true;
					model.albumNmae = this.albumNmae;
				}
				uni.navigateTo({
					url: '../details-page/details-page?model=' + this.$encodeJson(model)
				});
			}
		},
		onShareAppMessage(res) {
			var title = '小伙伴们快来啊'
			let data = {
				title: title, //转发标题
				path: this.getShareStr(true),
				imageUrl: this.model.imageUrl, //转发图片
				success: function(res) {
					console.log('分享成功', res);
					uni.showToast({
						title: '分享成功'
					})
					// 分享成功的处理逻辑
				},
			}
			return data
		},
		onShareTimeline() {
			var title = '小伙伴们快来啊'
			return {
				title: title,
				query: this.getShareStr(false),
				imageUrl: this.model.imageUrl,
				success: function(res) {
					console.log('分享成功', res);
					this.showSharePopup = false;
					this.$refs.popup.close()
					uni.showToast({
						title: '分享成功'
					})
				},
				fail: function(err) {
					console.error('分享失败', err);
					// 分享失败的处理逻辑
				},
				complete: function(res) {
					console.log('分享结束', res);
					// 分享结束的处理逻辑
				} //转发图片
			}
		}
	}
</script>

<style lang="scss">
	.topImage {
		width: 100%;
		// height: 200px;
		// border-radius: 4px;
		overflow: hidden;
	}

	.btn {
		color: white;
		font-size: 32rpx;
		height: 70rpx;
		margin: 20rpx 30rpx 0rpx 30rpx;
		border-radius: 30rpx;
		box-shadow: 0rpx 0rpx 20rpx rgb(248, 205, 87);
	}
</style>